package com.cskaoyan.order.mq.delay;

import jdk.nashorn.internal.ir.ReturnNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;
import org.springframework.validation.ObjectError;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @author: 杨庆
 * @since: 2022.9.23 16:50
 * @description:
 */

@Component
@Slf4j
public class DelayOrderCannelProducer {

    private DefaultMQProducer producer;

    //初始化： 1 配置类  2 自己初始化
    @PostConstruct
    public void inti() {
        producer = new DefaultMQProducer("delay_order_producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean sendDelayOrderMessage(String orderId) {
        log.info("start send delay orderMessage...{}", orderId);
        //准备发送的延迟消息

        Message message = new Message();
        message.setTopic("delay_order");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));
        //TODO 设置时间的延迟级别  int只是指定时间的一个级别
        // 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        // 1  2  3    4  5  6 7   8  9  10 11 12 13 14  15  16  17 18
        // 测试时候10s 实际是30m
        message.setDelayTimeLevel(6);
        SendResult sendResult = null;
        try {
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            log.info("send delay orderMessage..success.{}",orderId);
            return true;
        }
        log.info("send delay orderMessage..failed...{}",orderId);
        return false;
    }
}
